//
//  TileLoader.m
//  MapEdit
//
//  Created by Steven Canfield on 15/06/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "TileLoader.h"


@implementation TileLoader
- (id)initWithTilesetName:(NSString *)tileName palette:(ColorPalette *)pal mapData:(TileMap *)map
{
	self = [super init];
	
	if( self ) {
	
		NSData * tilePieceData = [[NSData alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@.vr4", tileName]];
		TilePieceList * pieceList = [[TilePieceList alloc] initWithData:tilePieceData];

		NSData * tileData = [[NSData alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@.vx4", tileName]];
		TileList * tileList = [[TileList alloc] initWithData:tileData];
		
		NSData * tileGroupData = [[NSData alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@.cv5", tileName]];
		TileGroupList * groupList = [[TileGroupList alloc] initWithData:tileGroupData];
		
		int WIDTH  = [map width];
		int HEIGHT = [map height];
		
		int X = 0;
		int Y = 0;

		NSImage * image = [[NSImage alloc] initWithSize:NSMakeSize( WIDTH * 32, HEIGHT * 32 )];
		[image lockFocus];
		
		NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];


		for( X = 0; X < WIDTH; X++ ) {
			for( Y = 0; Y < HEIGHT; Y++ ) {
				u_int16_t mapTileID = [map tileAtX:X Y:Y];
				int tileIndex = [groupList indexForGroup:(mapTileID / 16) member:(mapTileID % 16)];
				
				tile_t tile = [tileList tileAtIndex: tileIndex ];
				
				int tileX = 0;
				int tileY = 0;
				for( tileX = 3; tileX >= 0; tileX-- ) {
					for( tileY = 0; tileY < 4; tileY++ ) {
						BOOL flipTile = (tile.micro_tiles[(3-tileY) * 4 + tileX] % 2 == 0 );
						int tilePieceIndex = ( tile.micro_tiles[(3-tileY) * 4 + tileX] / 2 );
						tile_piece_t piece = [pieceList pieceAtIndex: tilePieceIndex ];
						int subTileX;
						int subTileY;
						for( subTileX = 0; subTileX < 8; subTileX++ ){
							if( flipTile ) {
								for( subTileY = 0; subTileY < 8; subTileY++ ) {
									NSColor * c = [pal colorAtIndex:piece.pixels[subTileY][7-subTileX]];
									int XToDraw = (X*32+tileX*8+(7-subTileX));
									int YToDraw = (32 * HEIGHT - (Y*32+tileY*8+(7 - subTileY)));
									[imageRep setColor:c atX:XToDraw y:YToDraw];
								}
							} else {
								for( subTileY = 0; subTileY < 8; subTileY++ ) {
									NSColor * c = [pal colorAtIndex:piece.pixels[subTileY][7-subTileX]];
									int XToDraw = (X*32+tileX*8+(7-subTileX));
									int YToDraw = (32 * HEIGHT - (Y*32+tileY*8+subTileY));
									[imageRep setColor:c atX:XToDraw y:YToDraw];
								}
							}
						}
					}
				}
				
			}
		}
		
		[image unlockFocus];
		
		NSData *picData;
		picData = [imageRep representationUsingType: NSPNGFileType
					 properties: nil];
		NSString * fileName = @"/Users/scanfield/mapout.png";
		[picData writeToFile:fileName atomically:YES];


		
		
		/*NSData * tileData = [[NSData alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@.vr4", tileName]];
		
		int dataIndex = 0;
		int tileSize = sizeof( u_int8_t ) * 64;
		
		int numberOfTiles = [tileData length] / tileSize;
		NSLog(@"%i Tiles", numberOfTiles);
		
	//	NSImage * image = [[NSImage alloc] initWithSize:NSMakeSize( 512, 3797 )];
	//	[image setCachedSeparately:NO];
	//	[image lockFocus];
		
	//	NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
		
		int dstX = 0;
		int dstY = 0;
		
		int tileNumber = 0;
		
		u_int8_t ** micro_tiles = malloc( sizeof( u_int8_t * ) * numberOfTiles );
		while( dataIndex < [tileData length]   ){
			
			u_int8_t * micro_tile = malloc( tileSize );
			[tileData getBytes:micro_tile range:NSMakeRange( dataIndex, tileSize )];
			
			micro_tiles[ tileNumber ] = micro_tile;
			
			int x, y;
			for( x = 0; x < 8; x++ ) {
				for( y =0; y < 8; y++ ) {
					u_int8_t index = micro_tile[x + (y * 8)];
					//[imageRep setColor:[pal colorAtIndex:index] atX:dstX+x y:dstY+y];
				}
			}
			
			dataIndex += tileSize;
			
			tileNumber++;
			
			dstX+=8;
			
			if( dstX >= 504 ) {
				dstX = 0;
				dstY+=8;
			}
		}
		
		
		NSData * tileGroupFile = [[NSData alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@.cv5", tileName]];
		
		
		int numEntries = [tileGroupFile length] / ( 32 + 20 );
		NSLog(@"%i entries in the group file", numEntries );
		u_int16_t ** tileGroups = malloc( sizeof( u_int16_t * ) * numEntries );
		
		dataIndex = 0;
		int groupCount = 0;
		while( dataIndex < [tileGroupFile length] ) {
			dataIndex += 20; // skip 20 bytes!
			u_int16_t * thisGroup = malloc( sizeof( u_int16_t ) * 16 );
			[tileGroupFile getBytes:thisGroup range:NSMakeRange( dataIndex , sizeof( u_int16_t ) * 16 )];
			tileGroups[ groupCount ] = thisGroup;
			dataIndex += sizeof( u_int16_t ) * 16;
			groupCount++;
		}
		
		NSLog(@"tileGroups[4][0] = %i", tileGroups[4][0]);
		
		NSLog(@"Loaded %i groups", groupCount );
		
		 Now We Need To Load "MiniTiles", which are 32x32 tiles made up from microtiles /
		
		NSData * miniTiles = [[NSData alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@.vx4", tileName]];
		
		//u_int32_t * miniTileStorage = malloc( sizeof( u_int32_t * ) * ([miniTiles length] / sizeof( u_int16_t )));
		
		NSMutableData * miniTileStorage = [[NSMutableData alloc] init];
		u_int32_t thisMiniTile[32][32];
		
		NSLog(@"%i", sizeof( thisMiniTile ));
		
		dataIndex = 0;
		int x, y;
		int BaseX;
		int BaseY;
		int fileIndex = 0;
		while( dataIndex < [miniTiles length] ) {
			for( x=3; x >= 0; x-- ) {
				for( y=0; y < 4; y++ ) {
					u_int16_t microTileIndex;
					[miniTiles getBytes:&microTileIndex range:NSMakeRange( dataIndex, sizeof( u_int16_t ) )];
					
					dataIndex += sizeof( u_int16_t );
					
					BOOL flip = microTileIndex % 2;
					microTileIndex = microTileIndex / 2;
					
					if( microTileIndex > numberOfTiles ) {
						NSLog(@"Index too big, %i, %i", microTileIndex, numberOfTiles );
					}
					
					BaseX = x*8, BaseY = y*8;
					int x2;
					int y2;
					if ( flip)
					{
						for (x2=0; x2<8; x2++) for (y2=0; y2<8; y2++)
							thisMiniTile[BaseX + x2][BaseY + y2] = micro_tiles[microTileIndex][ (7-x2) + ((7-y2) * 8)];
					} else { // normal
						for ( x2=0; x2<8; x2++) for ( y2=0; y2<8; y2++)
							thisMiniTile[BaseX + x2][BaseY + y2] = micro_tiles[microTileIndex][ (7-x2 ) + ( y2 * 8 )];
					}
				}
			}
			
		//	miniTileStorage[fileIndex] = thisMiniTile;
			[miniTileStorage appendBytes:thisMiniTile length:sizeof( thisMiniTile )];
			fileIndex++;
			
		}
		
		NSLog(@"%i minitiles loaded", fileIndex);
		
		NSImage * image = [[NSImage alloc] initWithSize:NSMakeSize( [map width] * 32, [map height] * 32 )];
		[image lockFocus];
		
		NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
		int xi, yi;
		for(  x = 0 ; x < [map width]; x++ ) {
			for( y = 0; y < [map height]; y++ ) {	
				u_int16_t tile = [map tileAtX:x Y:y];
				
				int index = tileGroups[ tile / 16][ tile % 16];
				
				u_int32_t minitile[32][32];
				
		//		minitile = miniTileStorage[ index ];
				[miniTileStorage getBytes:minitile range:NSMakeRange( sizeof( minitile ) * index, sizeof( minitile ))];
				
				for( xi = 0 ; xi < 32; xi++ ) {
					for( yi = 0; yi < 32; yi++ ) {
						int colorIndex = minitile[x][y];
						if( colorIndex >= 256 ) {
							[imageRep setColor:[pal colorAtIndex:0] atX:(x * 32 + xi) y:(y * 32 + yi)];
						} else {
							[imageRep setColor:[pal colorAtIndex:colorIndex] atX:(x * 32 + xi) y:(y * 32 + yi)];
						}
					}
				}				
			}
		}
		
		[image unlockFocus];
		
		NSData *picData;
		picData = [imageRep representationUsingType: NSPNGFileType
					 properties: nil];
		NSString * fileName = [NSString stringWithFormat:@"/Users/scanfield/mapout.png", fileIndex ];
		[picData writeToFile:fileName atomically:YES];


	}
	*/
//		

//		
//		
	}
	return self;
}
@end
